﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using Microsoft.Xna.Framework.Media;
using Coding4Fun.Phone.Controls;

namespace MyDeeWeibo.Classes
{
    public class SavePicToPhone
    {
        private readonly Uri savedSource;
        private readonly string filePath;
        private const string CacheDirectory = "CachedImages";

        public SavePicToPhone(Uri savedSource)
        {
            this.savedSource = savedSource;
            //文件路径
            filePath = Path.Combine(CacheDirectory, savedSource.AbsolutePath.TrimStart('/').Replace('/', '_'));
            SavePictureToLib();
        }

        private void SavePictureToLib()
        {
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(filePath, FileMode.Open, FileAccess.Read))
                {
                    try
                    {
                        MediaLibrary mediaLibrary = new MediaLibrary();
                        Picture pic = mediaLibrary.SavePicture("deeweibo_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg", fileStream);
                        fileStream.Close();
                        var messagePrompt = new MessagePrompt
                        {
                            Title = "提示",
                            Message = "保存成功",
                        };
                        messagePrompt.Show();
                    }
                    catch
                    {
                        var messagePrompt = new MessagePrompt
                        {
                            Title = "提示",
                            Message = "保存失败",
                        };
                        messagePrompt.Show();
                    }
                    finally
                    {
                        fileStream.Close();
                    }
                }
            }
        }
    }
}
